package com.moss.cloud.common.file.utils;

import com.alibaba.fastjson2.JSONObject;
import com.moss.cloud.common.file.constant.Constant;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 腾讯云存储
 *
 * @author 瑾年
 * @date 2018-10-30
 */
@Slf4j
public class TencentUtil {

    /**
     * 文件上传
     *
     * @param inputStream
     * @param cosClient
     * @param bucketName
     * @param fileName
     * @return
     */
    @SneakyThrows
    public static String tencentUpload(InputStream inputStream, COSClient cosClient, String bucketName, String fileName, String region) {
        String path = Constant.HTTP_PREFIX + bucketName + Constant.SPLIT + Constant.TENCENT_BASE_COS + Constant.SPLIT + region +
                Constant.SPLIT + Constant.TENCENT_BASE_URL;
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength((long)inputStream.available());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream,
                metadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info("腾讯云存储文件上传成功，响应内容:{}", JSONObject.toJSONString(putObjectResult));
        cosClient.shutdown();
        return path + fileName;
    }

    /**
     * 删除文件
     *
     * @param cosClient
     * @param imgName
     * @param bucketName
     */
    public static void delObject(COSClient cosClient, String imgName, String bucketName) {
        cosClient.deleteObject(bucketName, imgName);
        cosClient.shutdown();
    }
}
 
